﻿using KhoaLuan.Areas.Admin.ActionFilters;
using KhoaLuan.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KhoaLuan.Areas.Admin.Controllers
{
    [Security]
    public class UserController : Controller
    {
        //
        // GET: /Admin/User/
        public ApplicationDbContext db = new ApplicationDbContext();
        public UserManager<ApplicationUser> UserManager { get; private set; }

        public UserController()
        {
            UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        }
        public ActionResult Index()
        {
            ViewBag.Users = db.Users;

            var model = new ApplicationUser();
            return View(model);
        }
        public ActionResult Insert(ApplicationUser model, String newPassword1, String newPassword2)
        {
            if (newPassword1 != newPassword2)
            {
                ModelState.AddModelError("", "Xác nhận mật khẩu không đúng !");
            }
            else
            {
                var result = UserManager.Create(model, newPassword1);
                if (result.Succeeded)
                {
                    ModelState.AddModelError("", "Thêm mới thành công !");
                }
                else
                {
                    ModelState.AddModelError("", "Thêm mới thất bại !");
                }
            }

            ViewBag.Users = db.Users;
            return View("Index", model);
        }
        public ActionResult Update(ApplicationUser model, String password, String newPassword1, String newPassword2)
        {
            if (newPassword1 != newPassword2)
            {
                ModelState.AddModelError("", "Xác nhận mật khẩu mới không đúng !");
            }
            else
            {
                var user = UserManager.Find(model.UserName, password);
                if (user != null)
                {
                    UserManager.ChangePassword(user.Id, password, newPassword1);
                }
                else
                {
                    ModelState.AddModelError("", "Sai mật khẩu cũ !");
                }
            }
            ViewBag.Users = db.Users;
            return View("Index", model);
        }
        public ActionResult Delete(String Id)
        {
            ApplicationUser model = db.Users.Find(Id);
            db.Users.Remove(model);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Edit(String Id)
        {
            var model = db.Users.Find(Id);
            ViewBag.Users = db.Users;
            return View("Index", model);
        }


	}
}